package main

import (
	"encoding/json"
	"fmt"
	"log"

	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/ethclient"
)

func main() {
	// 连接到以太坊节点
	client, err := ethclient.Dial("https://polygon-bor-rpc.publicnode.com") // Polygon节点地址
	if err != nil {
		log.Fatal(err)
	}

	// 智能合约的ABI和地址
	abi, err := json.Marshal([]byte(`[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":true,"internalType":"address","name":"nftContract","type":"address"},{"indexed":false,"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"NFTStaked","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":true,"internalType":"address","name":"nftContract","type":"address"},{"indexed":false,"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"NFTUnstaked","type":"event"},{"inputs":[{"internalType":"address","name":"user","type":"address"},{"internalType":"address","name":"nftContract","type":"address"}],"name":"getStakedNFTs","outputs":[{"internalType":"uint256[]","name":"","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"onERC721Received","outputs":[{"internalType":"bytes4","name":"","type":"bytes4"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"nftContract","type":"address"},{"internalType":"uint256[]","name":"tokenIds","type":"uint256[]"}],"name":"stakeNFTs","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"nftContract","type":"address"},{"internalType":"uint256[]","name":"tokenIds","type":"uint256[]"}],"name":"unstakeNFTs","outputs":[],"stateMutability":"nonpayable","type":"function"}]`)) // 从智能合约的ABI JSON中获取
	if err != nil {
		log.Fatal(err)
	}
	contractAddr := "0x76B6bFFd69D0568756fa4B30ab07B0445d0D888f" // 分贝智能合约地址

	// 解析ABI和地址
	parsedABI, err := abi.ABI(string(abi))
	if err != nil {
		log.Fatal(err)
	}

	contract := common.HexToAddress(contractAddr)

	// 创建合约实例
	instance, err := ethcontract.NewContract(parsedABI, contract, client, nil)
	if err != nil {
		log.Fatal(err)
	}

	// 调用智能合约函数查询ID为1的数量
	// 假设智能合约中有一个名为"balanceOf"的函数，接受一个地址作为参数并返回数量
	var result uint64
	data, err := instance.Call(nil, "balanceOf", common.HexToAddress("0xb794D5A1948A4C781C609Ea15510E98c17811CaF")) // 分贝查询的方法
	if err != nil {
		log.Fatal(err)
	}
	err = parsedABI.Unpack(&result, "balanceOf", data)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("The balance of ID 1 for your address is: %d\n", result)
}
